#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct stu
{
	char name[20];
	int age;
};

int cmp(const void* a, const void* b)
{
	return *(int*)a - *(int*)b;
}

void test1()
{
	int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
	int sz = sizeof(arr) / sizeof(arr[0]);

	qsort(arr, sz, sizeof(arr[0]), cmp);

	for (int i = 0; i < sz; ++i)
	{
		printf("%d ", arr[i]);
	}
}

int cmp_stu_age(const void* a, const void* b)
{
	return ((struct stu*)a)->age - ((struct stu*)b)->age;
}

int cmp_stu_name(const void* a, const void* b)
{
	return strcmp(((struct stu*)a)->name, ((struct stu*)b)->name);
}

void test2()
{
	struct stu s[3] = { {"zhangsan", 18}, {"lisi", 22}, {"wangwu", 20} };
	int sz = sizeof(s) / sizeof(s[0]);

	qsort(s, sz, sizeof(s[0]), cmp_stu_age);
}

void test3()
{
	struct stu s[3] = { {"zhangsan", 18}, {"lisi", 22}, {"wangwu", 20} };
	int sz = sizeof(s) / sizeof(s[0]);

	qsort(s, sz, sizeof(s[0]), cmp_stu_name);
}
//
//void bubble_sort(int* arr, int sz)
//{
//	for (int i = 0; i < sz - 1; ++i)
//	{
//		for (int j = 0; j < sz - 1 - i; j++)
//		{
//			if (arr[j] > arr[j + 1])
//			{
//				int tmp = arr[j];
//				arr[j] = arr[j + 1];
//				arr[j + 1] = tmp;
//			}
//		}
//	}
//}

//void test4()
//{
//	int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
//	int sz = sizeof(arr) / sizeof(arr[0]);
//
//	bubble_sort(arr, sz);
//
//	for (int i = 0; i < sz; i++)
//	{
//		printf("%d ", arr[i]);
//	}
//}

void Swap(char* buf1, char* buf2, size_t width)
{
	for (int i = 0; i < width; i++)
	{
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

void bubble_sort(void* bese, size_t sz, size_t width, int (*cmp)(const void*, const void*))
{
	for (size_t i = 0; i < sz - 1; ++i)
	{
		for (size_t j = 0; j < sz - 1 - i; j++)
		{
			if(cmp(((char*)bese) + j * width, ((char*)bese) + (j + 1) * width) > 0)
			{
				Swap(((char*)bese) + j * width, ((char*)bese) + (j + 1) * width, width);
			}
		}
	}
}

void test5()
{
	int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
	size_t sz = sizeof(arr) / sizeof(arr[0]);

	bubble_sort(arr, sz, sizeof(arr[0]), cmp);

	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
}

void test6()
{
	struct stu s[3] = { {"zhangsan", 18}, {"lisi", 22}, {"wangwu", 20} };
	int sz = sizeof(s) / sizeof(s[0]);

	bubble_sort(s, sz, sizeof(s[0]), cmp_stu_name);
}

int main()
{
	//test1();
	//test2();
	//test3();

	//test4();

	//test5();
	test6();

	return 0;
}

